import {
  Body,
  Controller,
  Get,
  Param,
  Post,
  Query,
  UseGuards,
} from '@nestjs/common';
import { WorkService } from './work.service';
import { AuthGuard } from '@nestjs/passport';
import { ApiOperation } from '@nestjs/swagger';
import { CurrentUser } from 'src/user/user.decorator';
import { UserSys } from 'src/user/userSys.entity';
import { And, FindOptionsWhere, In, LessThan, MoreThan } from 'typeorm';
import { Work, WorkStatus } from './work.entity';
import * as moment from 'moment';
import { RoleEnum } from 'src/role/role.enum';
@Controller('api/work')
@UseGuards(AuthGuard('jwt'))
export class WorkController {
  constructor(private readonly workService: WorkService) {}

  @Get('getmine')
  @ApiOperation({ summary: '获取我的工作量' })
  async getmine(
    @CurrentUser() user: UserSys,
    @Query('date') date: string,
    @Query('project') project: number,
  ) {
    const where: FindOptionsWhere<Work> = {
      user: {
        id: user.id,
      },
    };
    if (!!date) {
      const d = moment(date);
      where.createAt = And(
        MoreThan(d.format('YYYY-MM')),
        LessThan(d.add(1, 'month').format('YYYY-MM')),
      ) as any;
    }
    if (!!project) where.project = { id: Number(project) };
    const [data, count] = await this.workService.work.findAndCount({
      where,
      order: {
        id: 'DESC',
      },
      relations: ['approved', 'approved.user', 'project', 'user'],
    });
    return { data, count };
  }

  @Get(':id/del')
  @ApiOperation({ summary: '删除工作量' })
  async del(@Param('id') id: number, @CurrentUser() user: UserSys) {
    return await this.workService.work.delete({
      id,
      user: {
        id: user.id,
      },
      status: In([WorkStatus.applying, WorkStatus.reject]),
    });
  }

  @Post(':id/publish')
  @ApiOperation({ summary: '重发' })
  async republish(
    @CurrentUser() user: UserSys,
    @Body() body,
    @Param('id') id: number,
  ) {
    return await this.workService.work.update(
      {
        id,
        user: { id: user.id },
        status: In([WorkStatus.applying, WorkStatus.reject]),
      },
      {
        count: body.count,
        comment: body.comment,
        status: WorkStatus.applying,
        createAt: body.createAt,
      },
    );
  }

  @Post('getUserWork')
  @ApiOperation({ summary: '获取某一个员工的工作量' })
  async getUserWork(@Body() body: any) {
    const { userId, status, startTime, endTime } = body;
    
    // 构建查询条件
    const whereConditions: any = {};
    
    // 用户ID是必需的
    if (userId) {
      whereConditions.user = { id: userId };
    }
    
    // 状态是可选的
    if (status) {
      whereConditions.status = status;
    }
    
    // 时间范围是可选的
    if (startTime && endTime) {
      whereConditions.createAt = And(MoreThan(startTime), LessThan(endTime)) as any;
    } else if (startTime) {
      whereConditions.createAt = MoreThan(startTime) as any;
    } else if (endTime) {
      whereConditions.createAt = LessThan(endTime) as any;
    }
    
    return await this.workService.work.find({
      where: whereConditions,
      relations: ['user', 'project'],
      order: { createAt: 'DESC' },
    });
  }

  @Get('getwork')
  @ApiOperation({ summary: '获取工作量' })
  async getwork(
    @Query('status') status: WorkStatus,
    @CurrentUser() user: UserSys,
  ) {
    //项目经理获取部门项目
    //boos、职场经理可以访问所有
    //否则只能获取负责人项目
    if (!status) status = WorkStatus.applying;
    const where: FindOptionsWhere<Work> = {
      status,
      system: {
        id: user.system.id,
      },
    };
    if (user.role === RoleEnum.manager) {
      where.dept = { id: user.dept.id };
    } else if (user.role === RoleEnum.member) {
      where.project = {
        responsibility: {
          user: {
            id: user.id,
          },
        },
      };
    } else if (user.role !== RoleEnum.director && user.role !== RoleEnum.boos) {
      return [];
    }
    const data = await this.workService.work.find({
      where,
      relations: ['user', 'project', 'approved', 'dept'],
      order: {
        createAt: 'desc',
      },
    });
    return data;
  }

  @Post('examine')
  @ApiOperation({ summary: '审批工作量' })
  async examine(@Body() { ids, type, comment }, @CurrentUser() user: UserSys) {
    const result = await this.workService.work.update(
      {
        id: In(ids),
        system: {
          id: user.system.id,
        },
        status: WorkStatus.applying,
      },
      {
        status: type,
        approved: user,
        comment,
      },
    );
    return result;
  }
}
